Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    currentDate: new Date().getTime(),
    gender: 0,
    name: '',
    mobile: '',
    visitDate: '',
    houseInfo: '',
    houseList: [{
        name: '北京西三旗花园1号楼 101'
      },
      {
        name: '北京东村家园3号楼 302'
      },
      {
        name: '北京育新花园3号楼 703'
      },
      {
        name: '北京天通苑北苑8号楼 403'
      },
    ],
  },
  openHouseLayer() {
    this.getHouseList()
    this.setData({
      houseLayerVisible: true
    })
  },
  closeHouseLayer() {
    this.setData({
      houseLayerVisible: false
    })
  },
  openDateLayer() {
    this.setData({
      dateLayerVisible: true
    })
  },
  closeDateLayer() {
    this.setData({
      dateLayerVisible: false
    })
  },
  //查询审核通过的房屋
  async getHouseList() {
    const res = await wx.http.get('/house')
    console.log(res);
    this.setData({
      houseList: res.data,
    })
  },
  //选择房屋
  selectHouse(e) {
    const {
      name,
      id: houseId
    } = e.detail
    this.setData({
      houseInfo: name,
      houseId
    })
  },
  //选择日期
  selectDate(e) {
    // console.log(e);
    const time = e.detail
    this.setData({
      dateLayerVisible: false,
      visitDate: wx.utils.formatDate(time)
    })
  },
  // 填写名字
  verifyNmae() {
    const reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/
    const valid = reg.test(this.data.name.trim())
    if (!valid) wx.utils.toast('请输入正确的中文名')
    return valid
  },
  // 填写手机号
  verifyMobile() {
    const reg = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    const valid = reg.test(this.data.mobile.trim())
    if (!valid) wx.utils.toast('请输入正确的手机号')
    return valid
  },
  // 选择报修房屋
  verifyHouse() {
    const valid = this.data.houseInfo !== ''
    // 验证结果提示
    if (!valid) wx.utils.toast('请选择房屋信息!')
    // 返回验证结果
    return valid
  },
  //验证预约日期
  verifyDate() {
    const reg = /^\d{4}[-|/]\d{2}[-|/]\d{2}$/
    const valid = reg.test(this.data.appointment)
    if (!valid) wx.utils.toast('请选择访问日期')
    // 返回验证结果
    return valid
  },
  //提交表单
  async onSubmit() {
    if (!this.verifyHouse()) return
    if (!this.verifyNmae()) return
    if (!this.verifyMobile()) return
    // if (!this.verifyDate()) return
    const {
      houseId,
      name,
      gender,
      mobile,
      visitDate
    } = this.data
    await wx.http.post('/visitor', {
      houseId,
      name,
      gender,
      mobile,
      visitDate
    })
    wx.utils.toast('新增访问成功')
    wx.navigateTo({
      url: '/visitor_pkg/pages/passport/index?id=' + this.data.houseId,
    })
  }
})